﻿using System;
using Riba.MVVMSL;

namespace TestGUI
{
	public class Page2ViewModel : ViewModelBase
	{
		public RelayCommand CommandNavigateWizardBack { get; private set; }
		public RelayCommand CommandNavigateWizardForward { get; private set; }

		public Page2ViewModel()
		{
			//var ed = ExchangeData;

			if (!ExchangeDataDictionary.ContainsKey("WizardPagePrev"))
				ExchangeDataDictionary.Add("WizardPagePrev", null);
			if (!ExchangeDataDictionary.ContainsKey("WizardPageCurr"))
				ExchangeDataDictionary.Add("WizardPageCurr", null);
			if (!ExchangeDataDictionary.ContainsKey("WizardPageNext"))
				ExchangeDataDictionary.Add("WizardPageNext", typeof(WizardPage1));

			CommandNavigateWizardBack = new RelayCommand(OnNavigateWizardBack) { IsEnabled = true };
			CommandNavigateWizardForward = new RelayCommand(OnNavigateWizardForward) { IsEnabled = true };

			NavigatorLoaded += Page2ViewModel_NavigatorLoaded;
			ExchangeDataAvailable += Page2ViewModel_ExchangeDataAvailable;
		}

		void Page2ViewModel_ExchangeDataAvailable(object sender, ExchangeDataAvailableEventArgs e)
		{
			ExchangeDataDictionary["CurrentPage"] = typeof(Page2);
			PropertyChanged += Page2ViewModel_PropertyChanged;
		}

		void Page2ViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
		{
			IsDirty = true;
		}

		void Page2ViewModel_NavigatorLoaded(object sender, EventArgs e)
		{
			UpdateWizardPages();
			RaiseNavigateToView(new NavigateToViewEventArgs(ExchangeDataDictionary["WizardPageCurr"] as Type, AnimationMode.Forward));
		}

		private void OnNavigateWizardBack(object handler)
		{
			if (ExchangeDataDictionary["WizardPagePrev"] == null)
				return;

			UpdateWizardPages();
			RaiseNavigateToView(new NavigateToViewEventArgs(ExchangeDataDictionary["WizardPagePrev"] as Type, AnimationMode.Backward));
		}

		private void OnNavigateWizardForward(object handler)
		{
			if (ExchangeDataDictionary["WizardPageNext"] == null)
				return;

			UpdateWizardPages();
			RaiseNavigateToView(new NavigateToViewEventArgs(ExchangeDataDictionary["WizardPageNext"] as Type, AnimationMode.Forward));
		}

		private static void UpdateWizardPages()
		{
			if (ExchangeDataDictionary["WizardPageCurr"] == typeof(WizardPage2))
			{
				ExchangeDataDictionary["WizardPagePrev"] = typeof(WizardPage1);
				ExchangeDataDictionary["WizardPageNext"] = typeof(WizardPage3);
			}
			else if (ExchangeDataDictionary["WizardPageCurr"] == typeof(WizardPage3))
			{
				ExchangeDataDictionary["WizardPagePrev"] = typeof(WizardPage2);
				ExchangeDataDictionary["WizardPageNext"] = typeof(WizardPage3);
			}
			else
			{
				ExchangeDataDictionary["WizardPageCurr"] = typeof(WizardPage1);
				ExchangeDataDictionary["WizardPagePrev"] = typeof(WizardPage1);
				ExchangeDataDictionary["WizardPageNext"] = typeof(WizardPage2);
			}
		}
	}
}
